package cn.didi.feidi.androidorder.fragment.personal;


import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.jungly.gridpasswordview.GridPasswordView;
import com.xw.repo.XEditText;

import java.util.HashMap;
import java.util.Map;

import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.api.Api;
import cn.didi.feidi.androidorder.api.ApiResponse;
import cn.didi.feidi.androidorder.api.ErrorEvent;
import cn.didi.feidi.androidorder.assembly.CommomDialog;
import cn.didi.feidi.androidorder.core.ActionCallbackListener;
import cn.didi.feidi.androidorder.core.AppActionRequest;
import cn.didi.feidi.androidorder.fragment.FeidiBaseFragment;
import cn.didi.feidi.androidorder.manager.UserManager;
import cn.didi.feidi.androidorder.util.MD5Util;


public class FindBackPayPswByAccountPswFragment extends FeidiBaseFragment {

    private static String TAG = "FindBackPayPswByAcco";
    private final static int FIRST_STEP = 1;
    private final static int SECOND_STEP = 2;

    private final static int FINISH = 4;

    private int whereStep = FIRST_STEP;

    private LinearLayout firstStepInputAccountPsw;
    private LinearLayout secondStepInputNewPassword;

    private XEditText inputAccountPsw;
    private TextView toSecondStep;

    private TextView changePasswordTip;
    private TextView changePasswordTip2;
    private GridPasswordView gridPasswordView;
    private TextView saveNewPasswordBtn;

    private String newPasswordOne;
    private String newPasswordTwo;


    /**
     * 与activity关联，后面可考虑单例模式
     *
     * @param bundle
     * @return
     */
    public static FindBackPayPswByAccountPswFragment newInstance(Bundle bundle) {
        FindBackPayPswByAccountPswFragment fragment = new FindBackPayPswByAccountPswFragment();
        if (bundle != null)
            fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    protected View initFragment(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_find_back_pay_password_by_account_password, container, false);
        return rootView;
    }

    @Override
    protected void initViews(View rootView) {
        firstStepInputAccountPsw = (LinearLayout) rootView.findViewById(R.id.person_find_back_pay_password_by_account_psw_first_step);
        secondStepInputNewPassword = (LinearLayout) rootView.findViewById(R.id.person_find_back_pay_password_by_account_psw_second_step);

        inputAccountPsw = (XEditText) rootView.findViewById(R.id.person_find_back_pay_password_by_account_psw_input_account_psw);
        toSecondStep = (TextView) rootView.findViewById(R.id.person_find_back_pay_password_by_account_psw_to_second_step);

        changePasswordTip = (TextView) rootView.findViewById(R.id.person_find_back_pay_password_by_account_psw_Tip);
        changePasswordTip2 = (TextView) rootView.findViewById(R.id.person_find_back_pay_password_by_account_psw_Tip2);
        gridPasswordView = (GridPasswordView) rootView.findViewById(R.id.person_find_back_pay_password_by_account_psw_grid_password_view);
        saveNewPasswordBtn = (TextView) rootView.findViewById(R.id.person_find_back_pay_password_by_account_psw_save_new_pay_password);
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void addListener() {

        toSecondStep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //  检验密码
                checkPassword();
            }
        });

        gridPasswordView.setOnPasswordChangedListener(new GridPasswordView.OnPasswordChangedListener() {
            @Override
            public void onTextChanged(String psw) {

            }

            @Override
            public void onInputFinish(String psw) {
                if (whereStep == FIRST_STEP) {
                    newPasswordOne = psw;
                    gridPasswordView.clearPassword();
                    changePasswordTip.setText("再次填写以确认");
                    changePasswordTip2.setVisibility(View.GONE);
                    saveNewPasswordBtn.setVisibility(View.VISIBLE);
                    whereStep = SECOND_STEP;
                } else {
                    if (whereStep == SECOND_STEP) {
                        newPasswordTwo = psw;
                        if (!newPasswordOne.equals(newPasswordTwo)) {
                            makeToast("新密码输入不一致");
                            whereStep = FIRST_STEP;
                            gridPasswordView.clearPassword();
                            changePasswordTip.setText("请设定新密码");
                            changePasswordTip2.setVisibility(View.VISIBLE);
                            saveNewPasswordBtn.setVisibility(View.GONE);
                        } else {
                            InputMethodManager inputMethodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                            if (inputMethodManager.isActive()) {
                                inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
                            }
                            saveNewPasswordBtn.setBackgroundColor(Color.parseColor("#347cf1"));
                            whereStep = FINISH;
                        }
                    }
                }
            }
        });

        gridPasswordView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (whereStep == FINISH) {
                    makeToast("不可再次编辑");
                }
            }
        });

        saveNewPasswordBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (whereStep == FINISH) {
                    setNewPayPasswordInServer();
                } else {
                    makeToast("请完整输入新密码");
                    return;
                }
            }
        });
    }

    private void setNewPayPasswordInServer() {
        Map<String, String> params = new HashMap<>();

        params.put("userId", UserManager.getUserId());
        params.put("token", UserManager.getToken());
        params.put("password", MD5Util.GetMD5Code32Bit(inputAccountPsw.getText().toString().trim()));
        params.put("payPwd", MD5Util.GetMD5Code32Bit(newPasswordTwo));

        executeRequest(new AppActionRequest<>(Api.FIND_BACK_PAY_PWD_SET_PAY_PWD_BY_PWD, params,
                new TypeToken<ApiResponse<String>>() {
                }.getType(), new ActionCallbackListener<String>() {
            @Override
            public void onSuccess(String message, String data) {
                makeToast("已设置新密码");
                getActivity().finish();
            }

            @Override
            public void onFailure(int errorEvent, String message) {
                Log.d(TAG, "errorEvent:" + errorEvent + "message=" + message);

                makeToast("密码设置失败");
                getActivity().finish();
            }
        }));
    }

    private void showSecondStep(){
        firstStepInputAccountPsw.setVisibility(View.GONE);
        secondStepInputNewPassword.setVisibility(View.VISIBLE);
    }

    private void checkPassword(){
        Map<String, String> data = new HashMap<String, String>();
        data.put("userId", UserManager.getUserId());
        data.put("token", UserManager.getToken());
        data.put("password", MD5Util.GetMD5Code32Bit(inputAccountPsw.getText().toString().trim()));

        executeRequest(new AppActionRequest<String>(Api.FIND_BACK_PAY_PWD_BY_PWD, data, new TypeToken<ApiResponse<String>>() {
        }.getType(), new ActionCallbackListener<String>() {
            @Override
            public void onSuccess(String message, String data) {
                showSecondStep();
            }

            @Override
            public void onFailure(int errorEvent, String message) {
                Log.d(TAG, "REGISTER failure errorEvent: " + errorEvent + "message: " + message);
                switch (errorEvent) {
                    case ErrorEvent.NONE_USER:
                        makeToast("该未注册");
                        break;
                    case ErrorEvent.WRONG_PASSWORD:
                        showAccountPswFalseDialog();
                        break;
                    case ErrorEvent.PARAM_ACCESS_QUICK:
                        break;
                    case ErrorEvent.PARAM_ACCESS_ERROR_NET:
                        break;
                    default:
                        makeToast("捕捉到未知错误");
                        break;
                }
            }
        }));

    }

//    密码错误提示框
    private void showAccountPswFalseDialog(){
        new CommomDialog(getContext(), R.style.dialog, "密码输入错误", new CommomDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    inputAccountPsw.setText("");
                    dialog.dismiss();
                }
            }
        }, true, true).setPositiveButton("重新输入","#347cf1").show();
    }
}